<template>
  <el-card>
    <!-- 步骤条 -->
    <el-steps
      style="margin-bottom: 20px"
      :active="active"
      align-center
      finish-status="success"
    >
      <el-step title="设定考试基本信息"></el-step>
      <el-step title="配置考试题目"></el-step>
      <!-- <el-step title="预览试卷"></el-step> -->
    </el-steps>
    <!-- 设定考试基本信息 -->
    <el-form
      v-if="active === 0"
      ref="form"
      :model="form"
      label-position="left"
      label-width="80px"
      style="width: 480px"
    >
      <el-form-item label="考试课程">
        <el-autocomplete
          class="inline-input"
          v-model="form.examCourseName"
          :fetch-suggestions="querySearch"
          placeholder="请输入内容"
          @select="handleSelect"
          style="width: 100%"
        ></el-autocomplete>
      </el-form-item>
      <el-form-item label="考试名称">
        <el-input v-model="form.examName"></el-input>
      </el-form-item>
      <el-form-item label="参考条件">
        <el-checkbox-group v-model="form.conditions">
          <el-checkbox label="选择该课程的同学" name="type"></el-checkbox>
          <el-checkbox label="学习进度达到80%" name="type"></el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="考试日期">
        <el-date-picker
          v-model="form.examDate"
          type="datetimerange"
          :picker-options="pickerOptions"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          align="right"
        >
        </el-date-picker>
      </el-form-item>
    </el-form>
    <!-- 配置考试题目 -->
    <topic-edit
      :topicIds="topicIds"
      :operTopicIds="operTopicIds"
      :setCriterion="setCriterion"
      v-else-if="active == 1"
      :setOpenWindow="setOpenWindow"
    ></topic-edit>

    <!-- 预览试卷 -->
    <!-- <div v-else-if="active == 2">
      <em>预览地址：</em
      setCriterion(criterion){
      this.criterion = criterion;
    }
      ><a href="https://www.baidu.com" target="_blank">https://www.baidu.com</a>
    </div> -->

    <!-- 下一步按钮 -->
    <div class="toolbar">
      <el-button :disabled="active == 0" @click="() => active--"
        >上一步</el-button
      >
      <el-button class="next" type="primary" @click="next"
        >{{ active === 2 ? "完成" : "下一步" }}
      </el-button>
    </div>
  </el-card>
</template>

<script>
import TopicEdit from "@/components/TopicEdit.vue";
import { mapMutations } from "vuex";
const dayjs = require("dayjs");

export default {
  name: "TeacherExam",
  components: { TopicEdit },
  data() {
    return {
      active: 0,
      topicIds: {
        singleChoice: [],
        multipleChoice: [],
        trueOrFalse: [],
        blankQuestion: [],
        essayQuestion: [],
      },
      form: {
        conditions: [],
      },
      criterion: {},
      loading: false,
      alternativeCourses: [],
      openWindow: null,
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
    };
  },
  methods: {
    ...mapMutations("windowAbout", ["CLOSE"]),
    next() {
      // if (this.active++ > 2) this.active = 0;
      if (this.active === 1) {
        //  删除那个新开的页签
        if (
          Object.keys(this.criterion).length === 0 &&
          !this.isTopicIdsEmpty()
        ) {
          alert("需要设置评分标准");
          return;
        }
        // this.openWindow.close();
        this.CLOSE();
      }
      if (this.active === 2) {
        // 上传考试
        const { teacher_id } = JSON.parse(localStorage.getItem("userInfo"));
        //处理examInfo
        this.form["examStart"] = dayjs(this.form.examDate[0]).format(
          "YYYY-MM-DD HH:mm:ss"
        );
        this.form["examEnd"] = dayjs(this.form.examDate[1]).format(
          "YYYY-MM-DD HH:mm:ss"
        );

        const data = {
          examInfo: this.form,
          topics: this.topicIds,
          criterion: this.criterion,
        };
        this.axios
          .post(
            `${this.$reqPrefix}/createExamination`,
            {
              teacher_id,
              course_id: this.form.examCourse,
              data,
            },
            {
              headers: {
                "Content-Type": "application/json;charset=UTF-8",
              },
            }
          )
          .then((res) => {
            this.$codeJudge(res.data.code, "创建成功", "创建失败");
          })
          .finally(() => {
            this.active = 0;
            this.form = {
              conditions: [],
            };
            this.topicIds = {};
          });
      }
      this.active = this.active + 1;
    },
    remoteMethod() {},
    operTopicIds(topicType, topicID) {
      if (!this.topicIds[topicType]) {
        console.log("未有这种题型");
        return;
      }
      this.topicIds[topicType].push(topicID);
    },
    setOpenWindow(ow) {
      this.openWindow = ow;
    },
    setCriterion(criterion) {
      this.criterion = criterion;
    },
    isTopicIdsEmpty() {
      let flag = true;
      for (const key in this.topicIds) {
        // console.log(key);
        if (this.topicIds[key].length > 0) {
          flag = false;
          break;
        }
      }
      return flag;
    },
    // 异步查询的回调
    querySearch(queryString, cb) {
      const alternativeCourses = this.alternativeCourses;
      var results = queryString
        ? alternativeCourses.filter(
            (course) =>
              course.value.toLowerCase().indexOf(queryString.toLowerCase()) ===
              0
          )
        : alternativeCourses;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    //异步查询的回调的依赖
    // createFilter(queryString) {
    //   return
    //   }
    // },
    handleSelect(item) {
      // console.log(item);
      this.form.examCourse = item.course_id;
    },
  },
  mounted() {
    // 初始化
    const { teacher_id } = JSON.parse(localStorage.getItem("userInfo"));
    this.$http
      .get(`${this.$reqPrefix}/getTeachCourse?teacher_id=${teacher_id}`)
      .then((res) => {
        const courses = res.data.data;
        courses.map((v) => {
          this.alternativeCourses.push({
            course_id: v.course_id,
            value: v.name,
          });
        });
      });
  },
};
</script>

<style lang='less' scoped>
.el-card {
  height: fit-content;
  min-height: 100%;
  position: relative;
  overflow: auto;
  border: none;
  :deep(.el-card__body) {
    padding-bottom: 80px;
  }

  .toolbar {
    position: absolute;
    background-color: #fff;
    bottom: 20px;
    right: 20px;
  }
}
</style>